import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';

// 创建新的异步action
export const fetchUnreadCount = createAsyncThunk(
    'xxx',
    async () => {
        try {
            // await new Promise(resolve => setTimeout(resolve, 2000));
            // return Math.floor(Math.random() * 20);

            return new Promise(resolve => setTimeout(() => {
                resolve(Math.floor(Math.random() * 20));
            }, 2000));
        } catch (error) {
            throw error;
        }
    }
);

const settingSlice = createSlice({
    name: 'setting',
    initialState: {
        username: '张三',
        unReadCount: 0,
        loading: false,
    },
    reducers: {
        changeUserName: (state, action) => {
            state.username = action.payload;
        },
    },
    extraReducers: (builder) => {
        builder.addCase(fetchUnreadCount.pending, (state) => {
            state.loading = true;
        });
        builder.addCase(fetchUnreadCount.fulfilled, (state, action) => {
            state.loading = false;
            state.unReadCount = action.payload;
        });
        builder.addCase(fetchUnreadCount.rejected, (state, action) => {
            state.loading = false;
        });
    }
});

export const { changeUserName } = settingSlice.actions;
export default settingSlice.reducer;